package com.sz.sendmsg.config;

import com.sz.sendmsg.entity.Permission;
import com.sz.sendmsg.realm.ShiroRealm;
import com.sz.sendmsg.service.ShiroService;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Configuration
public class ShiroConfig {
    @Autowired
    ShiroService shiroService;
    @Bean("realm")
    public Realm getRealm(){
        return new ShiroRealm();
    }
    @Bean("securityManager")
    public DefaultWebSecurityManager getSecurityManager(@Qualifier("realm") Realm realm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(realm);
        return defaultWebSecurityManager;
    }
    @Bean
    public ShiroFilterFactoryBean getFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        shiroFilterFactoryBean.setFilterChainDefinitionMap(permsMap());
        shiroFilterFactoryBean.setLoginUrl("/login/none");
        shiroFilterFactoryBean.setUnauthorizedUrl("/auth/none");
        return shiroFilterFactoryBean;
    }
    public Map<String,String> permsMap(){
        Map<String,String> map = new LinkedHashMap<String,String>();
        map.put("/login","anon");
        List<Permission> permissionList = shiroService.getPermissions();
        for (Permission permission:permissionList) {
            map.put(permission.getResourceUrl(),"perms["+ permission.getPermissionFlag()+"]");
        }
        return map;
    }
}
